from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import timezone
from django.core.cache import cache
import markdown

# Create your models here.
User = get_user_model()

class Article(models.Model):
    title = models.CharField(verbose_name='文章标题', max_length=150)
    content = models.TextField(verbose_name='文章内容')
    author = models.ForeignKey(verbose_name='作者', to=User, on_delete=models.PROTECT)
    category = models.ForeignKey(verbose_name='分类', to='Category', on_delete=models.SET_NULL, null=True, blank=True)
    tags = models.ManyToManyField(verbose_name='标签', to='Tag', blank=True)
    views = models.PositiveIntegerField(verbose_name='浏览量', default=0)

    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    update_at = models.DateTimeField(verbose_name='更新时间', auto_now=True)

    def __str__(self):
        return self.title
    
    def get_previous(self):
        return Article.objects.filter(id__lt=self.id).order_by('-id').first()

    def get_next(self):
        return Article.objects.filter(id__gt=self.id).order_by('id').first()

    def get_absolute_url(self):
        return reverse("blog:article_detail", kwargs={"pk": self.pk})

    def increase_views(self, request):
        user_id = request.user.id if request.user.is_authenticated else None
        ip_address = request.META.get('REMOTE_ADDR')
        cache_key = f'article_{self.id}_{user_id or ip_address}'
        last_viewed = cache.get(cache_key)

        current_time = timezone.now().timestamp()
        if last_viewed is None or (current_time - last_viewed) > 3600:
            self.views += 1
            self.save(update_fields=['views'])
            cache.set(cache_key, current_time, timeout=3600)

    def get_markdown_content(self):
        return markdown.markdown(self.content, extensions=[
            'extra',
            'codehilite',
            'toc',
        ])

class Category(models.Model):
    name = models.CharField(verbose_name='分类名称', max_length=10)

    def __str__(self):
        return self.name
    
    def get_absolute_url(self):
        return reverse("blog:category", kwargs={"pk": self.pk})

class Tag(models.Model):
    name = models.CharField(verbose_name='标签名称', max_length=10)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("blog:tag", kwargs={"pk": self.pk})

class Comment(models.Model):
    content = models.TextField(verbose_name='评论内容')
    article = models.ForeignKey(verbose_name='文章', to='Article', on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey(verbose_name='作者', to=User, on_delete=models.CASCADE)

    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    parent = models.ForeignKey(verbose_name='父评论', to='self', on_delete=models.CASCADE, null=True, blank=True, related_name='child_comments')
    reply_to = models.ForeignKey(verbose_name='回复对象', to='self', on_delete=models.CASCADE, null=True, blank=True, related_name='reply_comments')

    def __str__(self):
        return self.content[:20]
